package com.yl.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yl.resp.ReturnCodeEnum;
import com.yl.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 匿名用户访问无权限资源时的处理器
 */
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        String message = authException.getMessage();
        //将结果转换成JSON格式
        if(message.equals("Full authentication is required to access this resource")){
            message = ReturnCodeEnum.ACCESS_DENIED.getMessage();
        }
        String result = JSON.toJSONString(R.error(ReturnCodeEnum.ACCESS_DENIED.getCode(),message),SerializerFeature.DisableCircularReferenceDetect);
        //将结果保存到输出流里面
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
